WP.prototype.success = function (onFulfilled) {
    // 获取下this
    let self = this
    if (self.status === 'resolved') {
        onFulfilled(self.value)
    }

    // 如果异步执行则为pending状态
    if (self.status === 'pending') {
        // 保存回调函数
        self.onResolvedCallbacks.push(() => {
            onFulfilled(self.value)
        })
    }
    return self
}

WP.prototype.complete = function (onCompleted) {
    let self = this
    debugger
    self.onCompleteCallbacks.push(() => {
        debugger
        onCompleted(self.value || self.reason)
    })
    return self
}

WP.prototype.fail = function (onRejected) {
    let self = this
    if (self.status === 'rejected') {
        onRejected(self.reason)
    }

    // 如果异步执行则为pending状态
    if (self.status === 'pending') {
        // 保存回调函数
        self.onRejectedCallbacks.push(() => {
            onRejected(self.reason)
        })
    }
    return self
}

function WP (executor) {
    let self = this
    // 这里我们加入一个状态标识
    this.status = 'pending'
    this.value = undefined
    this.reason = undefined

    // 存储then中成功的回调函数
    this.onResolvedCallbacks = []
    this.onRejectedCallbacks = []
    this.onCompleteCallbacks = []

    function resolve (value) {
        if (self.status === 'pending') {
            self.value = value
            self.status = 'resolved'
            // 成功之后遍历then中所有的回调函数
            self.onResolvedCallbacks.forEach(fn => fn())
            // 成功之后遍历complete中所有的函数
            debugger
            self.onCompleteCallbacks.forEach(fn => fn())
        }
    }

    function reject (reason) {
        self.reason = reason
        if (self.status === 'pending') {
            self.reason = reason
            // 失败之后遍历then中所有的回调函数
            self.onRejectedCallkacks.forEach(fn => fn())
            // 失败之后遍历complete中所有的函数
            self.onCompleteCallbacks.forEach(fn => fn())
        }
    }

    // 这里对异常进行处理
    try {
        executor(resolve, reject)
    } catch (e) {
        reject(e)
    }
}

export default WP